import subprocess
import requests
import re
import json


def GetResponse(url):
    """发送请求

    参数:
        url (String): 请求的url
    """
    # 模拟浏览器
    headers = {
        # Cookie 用户信息，常用于检测是否有登录账号（用于获得更高清的视频）
        "Cookie":
        r"i-wanna-go-back=-1; buvid4=C5FEC776-600E-9B4E-017C-6D3B6B6FC66240525-023010620-aeheuapn6L3OukNLQV9dEg%3D%3D; DedeUserID=1472744881; DedeUserID__ckMd5=4f3de8d2e63e5afa; buvid_fp_plain=undefined; enable_web_push=DISABLE; buvid3=8AFA2CEE-6AC8-2C10-A520-35D0AB5D5AAC54372infoc; b_nut=1705753754; b_ut=5; _uuid=FBFC7DC3-102C8-37C9-74CA-D2BCDEA4B22F43410infoc; header_theme_version=CLOSE; hit-dyn-v2=1; LIVE_BUVID=AUTO7217075706590017; rpdid=|(m~Rl~)l~l0J'u~|~)uYm|l; CURRENT_QUALITY=80; is-2022-channel=1; FEED_LIVE_VERSION=V_HEADER_LIVE_NO_POP; CURRENT_FNVAL=4048; fingerprint=118e61b8b8ba2ecfb907ac099cfa0a7e; home_feed_column=4; SESSDATA=d033b889%2C1736931365%2C6bc93%2A72CjCyXtMLvBDswjTIUqLF8ZQ59hDgMWjj4o2a1BjQ_VpT4ck6ZcxjxfaDCbLDBiOJlDoSVnZ4RjRCdDhFbWFIU0lRNm1STWJHOElYQXlyYUlra0E2Vkg0VE1Pd3ZKT2J5eW5DLUNiQTh0bzBIX3FfWjc4YzVtXy1OanQtOWItMF9jbjRfdGdRYXVRIIEC; bili_jct=6c14f0d7f14c400210f4bbb1947c1d07; bili_ticket=eyJhbGciOiJIUzI1NiIsImtpZCI6InMwMyIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3MjE2NDAzNzcsImlhdCI6MTcyMTM4MTExNywicGx0IjotMX0.fjHwiZjHEeTV1_CYFX6MxuXRWxQ_rodz9mrR4u5ydFc; bili_ticket_expires=1721640317; browser_resolution=1375-773; buvid_fp=118e61b8b8ba2ecfb907ac099cfa0a7e; sensorsdata2015jssdkcross=%7B%22distinct_id%22%3A%2218b99e002fd9b0-06ba0c3877ad67c-4c657b58-1265047-18b99e002feaf1%22%2C%22first_id%22%3A%22%22%2C%22props%22%3A%7B%22%24latest_traffic_source_type%22%3A%22%E7%9B%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24latest_search_keyword%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%2C%22%24latest_referrer%22%3A%22%22%7D%2C%22identities%22%3A%22eyIkaWRlbnRpdHlfY29va2llX2lkIjoiMThiOTllMDAyZmQ5YjAtMDZiYTBjMzg3N2FkNjdjLTRjNjU3YjU4LTEyNjUwNDctMThiOTllMDAyZmVhZjEifQ%3D%3D%22%2C%22history_login_id%22%3A%7B%22name%22%3A%22%22%2C%22value%22%3A%22%22%7D%2C%22%24device_id%22%3A%2218b99e002fd9b0-06ba0c3877ad67c-4c657b58-1265047-18b99e002feaf1%22%7D; PVID=6; b_lsid=289E4D10F_190D411D64B; bmg_af_switch=1; bmg_src_def_domain=i1.hdslb.com; bp_t_offset_1472744881=956517000962637824; sid=4j5q81nr",
        # User-Agent 用户代理：表示浏览器/设备基本信息
        "User-Agent":
        r"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36 Edg/128.0.0.0"
    }
    # 发送请求
    response = requests.get(url=url, headers=headers)
    # 返回响应对象
    return response


def GetVideoInfo(link):
    """获取视频信息

    Args:
        link (String): 请求网址链接
    """
    # 发送请求
    response = GetResponse(url=link)
    # 获取响应数据
    html = response.text
    # 解析音视频数据
    info = re.findall(pattern=r"<script>window.__playinfo__=(.*?)</script>",
                      string=html)[0]
    # 数据转换为json
    json_data = json.loads(info)
    # 寻找 audio 链接
    audio_url = json_data['data']['dash']['audio'][0]['baseUrl']
    # 寻找 video 链接
    video_url = json_data['data']['dash']['video'][0]['baseUrl']
    # 解析视频基本信息
    title = re.findall(
        r'<title data-vue-meta="true">(.*?)_哔哩哔哩_bilibili</title>', html)[0]
    return title, audio_url, video_url


def save(title, audio_url, video_url):
    """保存视频

    Args:
        title (String): 视频标题
        audio (String): 音频链接
        video (String): 视频链接
    """
    # 发送请求 + 获取媒体内容
    audio_content = GetResponse(url=audio_url).content
    video_content = GetResponse(url=video_url).content
    with open('video\\' + title + '.mp3', mode='wb') as audio:
        audio.write(audio_content)
    with open('video\\' + title + '.mp4', mode='wb') as video:
        video.write(video_content)
    cmd = f'D:\ffmpeg.exe -i video/{title}.mp4 -i video/{title}.mp3 -c copy D:/123.mp4'
    subprocess.run(cmd, shell=True, check=True)


url = input()
a, b, c = GetVideoInfo(link=url)
save(a, b, c)
